import vtk
import numpy as np

# 假设你已经从文件中读取了以下数据
# 节点数据:节点编号、X坐标、Y坐标、Z坐标
nodes = np.loadtxt('./tests/data/nodes.txt',delimiter=',')

# 单元数据:单元编号、节点1、节点2、节点3、节点4
elements = np.loadtxt('./tests/data/elements.txt',delimiter=',').astype(int)

# 位移结果:节点编号、X方向位移、Y方向位移、Z方向位移
displacements = np.loadtxt('./tests/data/displace.txt',delimiter='\t')*100

# 创建 VTK 点集
points = vtk.vtkPoints()
for node in nodes:
    points.InsertNextPoint(node[1], node[2], node[3])

# 创建 VTK 单元集
cells = vtk.vtkCellArray()
for element in elements:
    cell = vtk.vtkQuad()  # 假设是四边形单元
    for i in range(4):
        cell.GetPointIds().SetId(i, element[i + 1] - 1)  # 节点编号从 1 开始,VTK 从 0 开始
    cells.InsertNextCell(cell)

# 创建 VTK 网格
grid = vtk.vtkUnstructuredGrid()
grid.SetPoints(points)
grid.SetCells(vtk.vtkQuad().GetCellType(), cells)

# 应用位移结果
for i, disp in enumerate(displacements):
    points.SetPoint(i, points.GetPoint(i)[0] + disp[1], points.GetPoint(i)[1] + disp[2], points.GetPoint(i)[2] + disp[3])

# 创建 VTK 数据集映射器
mapper = vtk.vtkDataSetMapper()
mapper.SetInputData(grid)

# 创建 VTK 演员
actor = vtk.vtkActor()
actor.SetMapper(mapper)
# 显示网格边框
actor.GetProperty().EdgeVisibilityOn()  # 显示边框
actor.GetProperty().SetEdgeColor(1, 0, 0)  # 设置边框颜色为白色
actor.GetProperty().SetLineWidth(2.0)  # 设置边框线宽为 2.0
# 创建 VTK 渲染器和渲染窗口
renderer = vtk.vtkRenderer()
render_window = vtk.vtkRenderWindow()
render_window.AddRenderer(renderer)

# 创建 VTK 渲染窗口交互器
render_window_interactor = vtk.vtkRenderWindowInteractor()
render_window_interactor.SetRenderWindow(render_window)

# 添加演员到渲染器
renderer.AddActor(actor)
renderer.SetBackground(0.1, 0.2, 0.3)  # 设置背景颜色

# 启动渲染窗口
render_window.Render()
render_window_interactor.Start()